﻿using MediatR;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;
using RBAC_Uthorization.Read.API.Application.Command.RoleCommand;
using RBAC_Uthorization.Read.API.DTO;
using RBAC_Uthorization.Read.API.DTO.Request;

namespace RBAC_Uthorization.Read.API.Application.CommandHandlers.RoleHandler
{
    public class RoleshowCommandHandlers : IRequestHandler<RoleShowCommand, ApiResult<PagingDto>>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly ILogger<RoleshowCommandHandlers> _logger;

        public RoleshowCommandHandlers(IRoleRepository roleRepository , ILogger<RoleshowCommandHandlers> logger)
        {
            _roleRepository = roleRepository;
            _logger = logger;
        }

        public async Task<ApiResult<PagingDto>> Handle(RoleShowCommand request, CancellationToken cancellationToken)
        {
            try
            {
                List<sys_role> roles;
                if (request.offlc_id == "10086")
                {
                    roles = await _roleRepository.GetAllAsync();
                }
                else
                {
                    roles = await _roleRepository.GetAllAsunc(x => x.offic_id == request.offlc_id && x.del_flag == 0 && x.sys_id == request.sys_id);
                }

                var totalCount = roles.Count;
                var totalPages = (int)Math.Ceiling(totalCount / (double)request.pageSize);
                var pagedRoles = roles.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

                var pagingDto = new PagingDto
                {
                    TotalPage = totalPages,
                    TotalCount = totalCount,
                    List = pagedRoles
                };

                return new ApiResult<PagingDto>() { Data = pagingDto };
             
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理RoleShowCommand时发生错误");
                return new ApiResult<PagingDto>(){Code = ResultCode.Fail,Message = "操作失败"};
            }
        }
    }
}
